<template>
    <div>
        <el-form :inline="true" :model="searchForm" style="margin-bottom: 20px;">
            <el-form-item label="关键字">
                <el-input v-model="searchForm.keywords" placeholder="请输入公告关键字" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
        </el-form>

        <el-table :data="notices" style="width: 100%">
            <el-table-column prop="id" label="公告ID" width="90" />
            <el-table-column prop="title" label="标题" />
            <el-table-column prop="updateTime" label="更新时间" />
            <el-table-column prop="adminId" label="管理员ID" width="120" />
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button size="small" @click="goDetail(scope.row)">查看</el-button>
              </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()

const searchForm = ref({
    keywords: ''
})
const notices = ref([])

// 获取所有公告
const fetchAllNotices = async () => {
    try {
        const res = await axios.get('http://localhost:8080/orgs/getAllAnnouncements')
        if (res.data && res.data.code === 200) {
            notices.value = res.data.data || []
        } else {
            notices.value = []
            ElMessage.error(res.data && res.data.msg ? res.data.msg : '获取公告失败')
        }
    } catch (e) {
        ElMessage.error('获取公告失败')
    }
}

// 搜索管理员公告
const handleSearch = async () => {
    if (!searchForm.value.keywords) {
        fetchAllNotices()
        return
    }
    try {
        const res = await axios.get(`http://localhost:8080/orgs/${searchForm.value.keywords}/announcements/searchByKeywords`)
        if (res.data && res.data.code === 200) {
            notices.value = res.data.data || []
        } else {
            notices.value = []
            ElMessage.error(res.data && res.data.msg ? res.data.msg : '搜索失败')
        }
    } catch (e) {
        ElMessage.error('搜索失败')
    }
}

// 重置
const resetSearch = () => {
    searchForm.value.keywords = ''
    fetchAllNotices()
}

const goDetail = (row) => {
  router.push({ name: 'AnnouncementDetail', params: { id: row.id } })
}

onMounted(fetchAllNotices)
</script>